using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Tryit.Models;

namespace Tryit.Services
{
    public class MaterialService
    {
        private readonly string _materialsDirectory;

        public MaterialService()
        {
            _materialsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config", "materials");
            if (!Directory.Exists(_materialsDirectory))
            {
                Directory.CreateDirectory(_materialsDirectory);
            }
        }

        /// <summary>
        /// 获取所有材料名称
        /// </summary>
        public List<string> GetAllMaterialNames()
        {
            try
            {
                var files = Directory.GetFiles(_materialsDirectory, "*.json");
                return files.Select(Path.GetFileNameWithoutExtension).ToList();
            }
            catch (Exception ex)
            {
                throw new Exception($"获取材料列表失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 保存材料
        /// </summary>
        public async Task SaveMaterialAsync(Material material)
        {
            try
            {
                material.UpdateTime = DateTime.Now;
                var filePath = Path.Combine(_materialsDirectory, $"{material.Name}.json");
                var json = JsonSerializer.Serialize(material, new JsonSerializerOptions { WriteIndented = true });
                await File.WriteAllTextAsync(filePath, json);
            }
            catch (Exception ex)
            {
                throw new Exception($"保存材料失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 加载材料
        /// </summary>
        public Material? LoadMaterial(string materialName)
        {
            try
            {
                var filePath = Path.Combine(_materialsDirectory, $"{materialName}.json");
                if (!File.Exists(filePath))
                    return null;

                var json = File.ReadAllText(filePath);
                return JsonSerializer.Deserialize<Material>(json);
            }
            catch (Exception ex)
            {
                throw new Exception($"加载材料失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 删除材料
        /// </summary>
        public async Task DeleteMaterialAsync(string materialName)
        {
            try
            {
                var filePath = Path.Combine(_materialsDirectory, $"{materialName}.json");
                if (File.Exists(filePath))
                {
                    await Task.Run(() => File.Delete(filePath));
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"删除材料失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 检查材料是否存在
        /// </summary>
        public bool MaterialExists(string materialName)
        {
            var filePath = Path.Combine(_materialsDirectory, $"{materialName}.json");
            return File.Exists(filePath);
        }

        /// <summary>
        /// 复制材料
        /// </summary>
        public async Task<Material> CopyMaterialAsync(string sourceMaterialName, string newMaterialName)
        {
            try
            {
                var sourceMaterial = LoadMaterial(sourceMaterialName);
                if (sourceMaterial == null)
                    throw new Exception($"源材料不存在: {sourceMaterialName}");

                var newMaterial = new Material(newMaterialName, $"{sourceMaterial.Description} (副本)");
                
                // 复制元素
                foreach (var element in sourceMaterial.Elements)
                {
                    var newElement = new MaterialElement
                    {
                        ElementName = element.ElementName,
                        Value = element.Value
                    };
                    newMaterial.Elements.Add(newElement);
                }

                await SaveMaterialAsync(newMaterial);
                return newMaterial;
            }
            catch (Exception ex)
            {
                throw new Exception($"复制材料失败: {ex.Message}");
            }
        }
    }
} 